<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-row type="flex">
        <el-col>
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品管理</el-breadcrumb-item>
          <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="mini" @click="goGoodsListPage"
            >返回</el-button
          >
        </el-col>
      </el-row>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 顶部消息提示区 -->
      <el-alert
        title="编辑商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏 填写商品信息区域 -->
      <el-form
        :model="editGoodFrom"
        :rules="editGoodFromRules"
        ref="editGoodFromRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          @tab-click="tabClicked"
          :before-leave="beforeTabLeave"
        >
          <!-- 基本信息的tab栏 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editGoodFrom.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="editGoodFrom.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="editGoodFrom.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="editGoodFrom.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <!-- options用来指定数据源  -->
              <!-- props用来指定配置对象 -->
              <el-cascader
                clearable
                v-model="editGoodFrom.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="parentCateChanged"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数的tab栏 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item1"
                  v-for="(item1, index1) in item.attr_vals"
                  :key="index1"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性的tab栏 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片的tab栏 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- action图片上传地址 -->
            <el-upload
              :file-list="editGoodFrom.pics"
              :action="uploadURL"
              :headers="headersObj"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :on-preview="handlePreview"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容的tab栏 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="editGoodFrom.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="addGoods" @click="editGoods"
              >修改商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialog"
      width="50%"
      class="previewImg"
    >
      <img :src="priviewPath" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取地址栏id
      id: 0,
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 绑定步骤条的索引
      activeIndex: '0',
      // 添加商品信息表单对象
      editGoodFrom: {
        goods_name: '',
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        // 上传商品图片数据
        pics: [],
        // 商品描述
        goods_introduce: '',
        attrs: [],
        goods_cat: []
      },
      // 添加商品信息表单验证规则对象
      editGoodFromRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 商品参数数据对象
      manyTabData: [],
      // 商品属性数据对象
      onlyTabData: [],
      // 图片上传地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传的请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制图片预览对话框的flag
      previewDialog: false,
      // 图片预览路径
      priviewPath: ''
    }
  },
  created() {
    this.id = this.getUrlKey('id')
    this.getGoodList()
    this.getCateList()
  },
  methods: {
    // 获取地址栏参数 id
    getUrlKey(name) {
      return (
        decodeURIComponent(
          (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
            location.href
          ) || [''])[1].replace(/\+/g, '%20')
        ) || null
      )
    },
    // 页面加载获取当前id商品信息
    async getGoodList() {
      const { data: res } = await this.$http.get('goods/' + this.id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取当前商品失败!')
      }
      // 遍历pics 添加name与url属性, 图片显示要用
      res.data.pics.forEach(item => {
        item.name = item.pics_id
        item.url = item.pics_big_url
      })
      this.editGoodFrom = res.data
      // 修改级联选择框的值
      this.editGoodFrom.goods_cat = this.editGoodFrom.goods_cat.split(',').map(Number)
    },
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表分类失败!')
      }
      // 把响应数据,赋值给 cateList
      this.cateList = res.data
    },
    // 获取商品参数列表
    async getParams(sel) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: sel
          }
        }
      )
      if (res.meta.status !== 200) {
        if (sel === 'many') {
          return this.$message.error('获取商品参数失败!')
        } else {
          return this.$message.error('获取商品属性失败!')
        }
      }
      if (sel === 'many') {
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 监听 返回按钮的编程式路由
    goGoodsListPage() {
      this.$router.push('/goods')
    },
    // 监听 tab栏切换前的钩子函数
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.editGoodFrom.goods_cat.length === 0) {
        this.$message.error('请填写商品分类!')
        return false
      }
    },
    // 监听 tab栏切换的点击事件
    tabClicked() {
      if (this.activeIndex === '1') {
        this.getParams('many')
      }
      if (this.activeIndex === '2') {
        this.getParams('only')
      }
    },
    // 监听 上传图片预览事件
    handlePreview(file) {
      console.log(file)
      // 1.缓存图片地址
      this.priviewPath = file.pics_big_url
      // 2.显示预览图片对话框
      this.previewDialog = true
    },
    // 监听 上传图片删除事件
    handleRemove(file, fileList) {
      this.editGoodFrom.pics = fileList
    },
    // 监听 上传图片成功事件
    handleSuccess(response) {
      // 拼接得到一个图片对象
      const picInfo = {
        url: response.data.url,
        name: '上传成功',
        pics_big_url: response.data.url,
        pic: response.data.tmp_path
      }
      this.editGoodFrom.pics.push(picInfo)
    },
    // 监听 添加商品按钮事件
    editGoods() {
      // 预验证
      // console.log(this.editGoodFrom)
      this.$refs.editGoodFromRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项!')
        }
        // 因为级联选择器绑定的goods_cat的值必须是数组,所以对请求参数对象进行拷贝
        const form = this.editGoodFrom
        // 1.对传递的参数进行处理,将goods_cat转换为字符串
        form.goods_cat = form.goods_cat.join(',')
        // 2.处理动态参数,以及静态属性
        // 因为获取到的商品数据内包涵attrs先清空再赋值
        form.attrs = []
        this.manyTabData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          form.attrs.push(newInfo)
        })
        this.onlyTabData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          form.attrs.push(newInfo)
        })
        // 调用接口
        const { data: res } = await this.$http.put('goods/' + this.id, form)
        if (res.meta.status !== 200) {
          return this.$message.error('添加商品失败!')
        }
        this.$message.success('修改商品成功!')
        this.$router.push('/goods')
      })
    },
    // 监听 级联选择框的值改变事件
    parentCateChanged() {
      if (this.editGoodFrom.goods_cat.length === 0) {
        this.editGoodFrom.goods_cat = []
        return
      }
      if (this.editGoodFrom.goods_cat.length !== 3) {
        this.editGoodFrom.goods_cat = []
        return this.$message.info('只允许添加三级分类!')
      }
    }
  },
  computed: {
    // 计算商品分类的id
    cateId() {
      if (this.editGoodFrom.goods_cat !== 0) {
        return this.editGoodFrom.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.addGoods {
  margin-top: 15px;
}
</style>
